package RSS.writer;

import RSS.bean.CommonInformationItem;
import RSS.buffer.NewsBuffer;
import RSS.dao.ProjectProperties;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @program: gitee4_socket
 * @description: 从缓存中取数据，写到磁盘( mongodb, 数据库  )
 * @author: zy
 * @create: 2024-07-24 15:48
 */
public class NewsWriterTask implements Runnable {
    private Logger log = Logger.getLogger(NewsWriterTask.class.getName());

    private String name; //RSS的源的名称,用来做磁盘文件的文件名

    private NewsBuffer buffer; //缓存

    private boolean flag = false;

    public NewsWriterTask(NewsBuffer buffer) {
        this.buffer = buffer;
        this.name = "未知新闻源";
    }

    public NewsWriterTask(NewsBuffer buffer, String name) {
        this.buffer = buffer;
        this.name = name;
    }

    @Override
    public void run() {
        //循环从buffer中取新闻，存到磁盘( mongodb )
        while (!flag && !Thread.currentThread().isInterrupted()) {
            CommonInformationItem item = null;
            try {
                item = buffer.get();   // 一直到缓存中去取数据
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (item == null) {
                System.out.println("暂无数据写入");
                continue;
            }
            //将此item写到磁盘.
            Path p = Paths.get(ProjectProperties.getInstance().getProperty("file.path") + item.getFileName());
            //流 :                创建一个缓冲字符流(因为可以一行一行的写数据 )        CREATE: 每次都新建文件
            try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.CREATE)) {
                writer.write(item.toString());
                writer.flush();
            } catch (IOException e) {
                log.error("保存信息失败:" + e);
            }
        }
    }
}
